<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">


          <a-col :md="4" :sm="5">
            <a-form-item label="异常类型">
              <a-select v-model="queryParam.abnormalType" placeholder="请选择异常类型">
                <a-select-option value>请选择异常类型</a-select-option>
                <a-select-option value="1">应急开闸</a-select-option>
                <a-select-option value="2">遥控器开闸</a-select-option>
                <a-select-option value="3">无入场纪录</a-select-option>
                <a-select-option value="4">取消出场</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="10">
            <a-form-item label="请选择车道">
            <a-select  :value="ArmName" :options="ArmOptions" @change="ArmSelect"
                       style="width:200px;">
            </a-select>
            </a-form-item>
          </a-col>


          <a-col :md="4" :sm="8">
            <a-form-item label="开始日期">
                      <a-date-picker   placeholder="开始日期"  @change="onChangeStartTime"/>
                      </a-form-item >
                    </a-col>

          <a-col :md="4" :sm="8">
            <a-form-item label="结束日期">
                <a-date-picker placeholder="结束日期" @change="onChangeEndTime" />
                </a-form-item >

            </a-col>

          <a-col :md="3" :sm="4">
            <a-form-item label="车牌号">
              <a-input v-model="queryParam.plateNo" placeholder="请输入车牌号"></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <a-form-item label="当班操作员">
              <a-input v-model="queryParam.workStationOperator" placeholder="请输入当班操作员"></a-input>
            </a-form-item>
          </a-col>


          <a-col :md="4" :sm="8" >
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>

            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('车场异常记录')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
          <a-menu-item key="2" @click="batchTOBlacklist"><a-icon type="delete"/>拉黑</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
           <a @click="handleDetails(record)">关联记录</a>

                    <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm title="确定加入黑名单吗?" @confirm="() => handleToBlacklist(record)">
                  <a>加入黑名单</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <parkCarAbnormalRecord-modal ref="modalForm" @ok="modalFormOk"></parkCarAbnormalRecord-modal>
  </a-card>
</template>

<script>
  import ParkCarAbnormalRecordModal from './modules/ParkCarAbnormalRecordModal'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import {deleteAction, getAction, downFile, httpAction, postAction} from '@/api/manage'
  import { filterObj } from '@/utils/util';

  export default {
    name: "ParkCarAbnormalRecordList",
    mixins:[JeecgListMixin],
    components: {
      ParkCarAbnormalRecordModal
    },
    data () {
      return {
        ParkCode: '',
        ArmName: '',
        ParkOptions: [{value: '', label: '请选择停车场'}],
        ArmOptions: [{value: '', label: '请选择车道'}],
        description: '车场异常记录管理页面',
        // 表头
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
           },
          {
            title: '车牌号',
            align:"center",
            dataIndex: 'plateNo'
           },
          {
            title: '识别车牌号',
            align:"center",
            dataIndex: 'identifyPlateNo'
           },

          {
            title: '车道名称',
            align:"center",
            dataIndex: 'armName'
           },
          {
            title: '操作员',
            align:"center",
            dataIndex: 'workStationOperator'
           },
        {
            title: '工作站名称',
            align:"center",
            dataIndex: 'workStationName'
           },
        {
            title: '识别图片',
            align:"center",
            dataIndex: 'identifyImgPath',
          customRender: (record) => {
            let r = record
            return (
                <img
                    style="max-width:35px;max-height:35px;min-height:20px;min-width:20px;text-align:center;cursor:pointer;border:1px #BFBFBF solid;padding: 2px 2px 2px 2px;background-color:white;"
                    preview=''
                    src={record}
                ></img>
            )
          }
           },
        {
            title: '抓拍图片',
            align:"center",
            dataIndex: 'imgPath',
            customRender: (record) => {
              let r = record
              return (
                  <img
                      style="max-width:35px;max-height:35px;min-height:20px;min-width:20px;text-align:center;cursor:pointer;border:1px #BFBFBF solid;padding: 2px 2px 2px 2px;background-color:white;"
                      preview=''
                      src={record}
                  ></img>
              )
            }
           },
        {
            title: '触发时间',
            align:"center",
            dataIndex: 'triggerTime'
           },
        {
            title: '异常类型',
            align:"center",
            dataIndex: 'abnormalType',
            customRender: function (t) {
              if(t===1) {
                return "应急开闸"
              }
              if(t===2) {
                return "遥控器开闸"
              }
              if(t===3) {
                return "无入场纪录"
              }
              if(t===4) {
                return "取消出场"
              }
            }
           },
          {
            title: '备注',
            align:"center",
            dataIndex: 'remark'
           },

          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            scopedSlots: { customRender: 'action' },
          }
        ],
		url: {
          ParkList: '/parking/parkInfo/list',
          ArmList: '/parking/parkArmInfo/parkArmInfoList',
          list: "/parkCarAbnormalRecord/list",
          delete: "/parkCarAbnormalRecord/delete",
          deleteBatch: "/parkCarAbnormalRecord/deleteBatch",
          exportXlsUrl: "/parkCarAbnormalRecord/exportXls",
          importExcelUrl: "/parkCarAbnormalRecord/importExcel",

          toBlacklist:"/parkCarAbnormalRecord/toBlacklist",
          toBlacklistBatch:"/parkCarAbnormalRecord/toBlacklistBatch"
       },
       queryParam: {
                "opTime_begin":"",
                "opTime_end":"",
                "type":"-1",

              },
              isorter:{
               column: 'createTime',
               order: 'desc',
             },
    }
  },
  computed: {
    importExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
   created(){

         this.keyupEnter()
   },
    mounted() {
      this.loadParkData()
      this.loadArmData()
    },
    methods: {
      handleToBlacklist(record){
        console.log(record.identifyPlateNo)
        const that = this
        if (record.identifyPlateNo == "_无_"){
          that.$message.warning("该牌号'_无_'不能被加入黑名单!")
        }else {

          postAction(that.url.toBlacklist,record).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
            }else {
              that.$message.warning(res.message)
            }
          })
        }

      },
      ParkSelect(value) {
        this.ParkCode = value
      },

      ArmSelect(value1) {
        this.ArmName = value1
      },

      loadParkData() {
        var Params = {}
        httpAction(this.url.ParkList, Params, "get").then((res) => {
          if (res.success) {
            this.ParkOptions = [{value: '', label: '请选择停车场'}]
            res.result.records.forEach((park) => {
              this.ParkOptions.push({
                value: park.parkCode,
                label: park.parkName
              })
            })
            this.ParkCode = this.ParkOptions[0].value
          }
        })
      },

      loadArmData() {
        var Params = {}
        httpAction(this.url.ArmList, Params, "get").then((res) => {
          if (res.success) {
            this.ArmOptions = [{value: '', label: '请选择车道'}]
            res.result.forEach((park) => {
              this.ArmOptions.push({
                value: park.armName,
                label: park.armName
              })
            })
            this.ArmName = this.ArmOptions[0].value
          }
        })
      },
      handleDetails(record) {

        this.item =record;
        debugger;

        if (this. item.enterBatchNumber === 'undefined'|| this.item.enterBatchNumber ==="" || this. item.enterBatchNumber === null){

          this.$message.error("未查询到关联记录");
          return
        }
        let batchNumber;
        this.$router.push({
          path:"/abnormalRecord/ParkCarAbnormalRecordDetailsList",
          query:{
                batchNumber : this.item.enterBatchNumber
          }
        })
      },

      handleExportXls(fileName){

            let startTime = this.queryParam.opTime_begin;
            let endTime = this.queryParam.opTime_end;
            let dayTime = startTime;
            if (startTime== "") {
                this.$message.error("请选择导出开始日期");
                return
            }
            if ( endTime == "") {
                this.$message.error("请选择导出结束日期");
                return
            }
             if (startTime != "" && endTime != "") {
              if (startTime != endTime) {
                this.$message.error("仅支持1天数据导出,请选择导出日期");
                return
              }
            }

            if(startTime=="" && endTime != ""){
               this.$message.error("请选择开始时间");
                return
            }

             if(startTime !="" && endTime == ""){
               this.$message.error("请选择结束时间");
                return
            }


            this.queryParam.dayTime = dayTime;
           fileName =  dayTime + fileName;
           let param = {...this.queryParam};
           if (this.queryParam.opTime_begin != "" && this.queryParam.opTime_end != "") {
                               param.createTime_begin = this.queryParam.opTime_begin + " 00:00:00";
                               param.createTime_end = this.queryParam.opTime_end + " 23:59:59";
                            }

          downFile(this.url.exportXlsUrl,param).then((data)=>{
            if (!data) {
              this.$message.warning("文件下载失败")
              return
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(new Blob([data]), fileName+'.xls')
            }else{
              let url = window.URL.createObjectURL(new Blob([data]))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', fileName+'.xls')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link); //下载完成移除元素
              window.URL.revokeObjectURL(url); //释放掉blob对象
            }
          })
        },


           onChangeStartTime(date, dateString) {
              this.queryParam.opTime_begin = dateString;
              },

              onChangeEndTime(date, dateString) {
                this.queryParam.opTime_end = dateString;
              },



        loadData(arg) {
          if(!this.url.list){
            this.$message.error("请设置url.list属性!")
            return
          }
          //加载数据 若传入参数1则加载第一页的内容
          if (arg === 1) {
            this.ipagination.current = 1;
          }
          var params = this.getQueryParams();//查询条件
          this.loading = true;
          getAction(this.url.list, params).then((res) => {
            if (res.success) {
              this.dataSource = res.result.records;
              this.ipagination.total = res.result.total;
            }
            if(res.code===510){
              this.$message.warning(res.message)
            }
            this.loading = false;
          })
        },

        searchQuery() {
                let startTime = this.queryParam.opTime_begin;
                let endTime = this.queryParam.opTime_end;

                if (startTime != "" && endTime != "") {
                  if (startTime > endTime) {
                    this.$message.error("开始时间不能大于结束时间");
                    return
                  }
                }

                if(startTime=="" && endTime != ""){
                   this.$message.error("请选择开始时间");
                    return
                }

                 if(startTime !="" && endTime == ""){
                   this.$message.error("请选择结束时间");
                    return
                }

                this.loadData(1);
            },

                getQueryParams(){

                var param = Object.assign({}, this.isorter, this.queryParam);
                param.field = this.getQueryField();
                param.pageNo = this.ipagination.current;
                param.pageSize = this.ipagination.pageSize;
                if (this.queryParam.opTime_begin != "" && this.queryParam.opTime_end != "") {
                   param.createTime_begin = this.queryParam.opTime_begin + " 00:00:00";
                   param.createTime_end = this.queryParam.opTime_end + " 23:59:59";
                }
                param.parkCode = this.ParkCode
                param.armName = this.ArmName
                // delete param.createTimeRange; // 时间参数不传递后台
                return filterObj(param);
              },

                loadData(arg) {
                  if(!this.url.list){
                    this.$message.error("请设置url.list属性!")
                    return
                  }
                  //加载数据 若传入参数1则加载第一页的内容
                  if (arg === 1) {
                    this.ipagination.current = 1;
                  }
                  var params = this.getQueryParams();//查询条件
                  this.loading = true;
                  getAction(this.url.list, params).then((res) => {
                    if (res.success) {
                      this.dataSource = res.result.records;
                      this.ipagination.total = res.result.total;
                    }
                    if(res.code===510){
                      this.$message.warning(res.message)
                    }
                    this.loading = false;
                  })
                },

              batchDel: function () {

              if(!this.url.deleteBatch){
                this.$message.error("请设置url.deleteBatch属性!")
                return
              }
              if (this.selectedRowKeys.length <= 0) {
                this.$message.warning('请选择一条记录！');
                return;
              } else {
                var ids = "";
                for (var a = 0; a < this.selectionRows.length; a++) {
                  ids += this.selectionRows[a].invateuserdetailId + ",";
                }
                var that = this;
                this.$confirm({
                  title: "确认删除",
                  content: "是否删除选中数据?",
                  onOk: function () {
                    deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
                      if (res.success) {
                        that.$message.success(res.message);
                        that.loadData();
                        that.onClearSelected();
                      } else {
                        that.$message.warning(res.message);
                      }
                    });
                  }
                });
              }
            },
      batchTOBlacklist(){
        if(!this.url.toBlacklistBatch){
          this.$message.error("请设置url.deleteBatch属性!")
          return
        }
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        } else {
          var ids = "";
          for (var a = 0; a < this.selectionRows.length; a++) {
            ids += this.selectionRows[a].id + ",";
          }
          var that = this;
          this.$confirm({
            title: "确认拉黑",
            content: "是否拉黑选中数据?",
            onOk: function () {
              deleteAction(that.url.toBlacklistBatch, {ids: ids}).then((res) => {
                if (res.success) {
                  that.$message.success(res.message);
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.message);
                }
              });
            }
          });
        }
      },
            handleDelete: function (invateuserdetailId) {
              if(!this.url.delete){
                this.$message.error("请设置url.delete属性!")
                return
              }
              var that = this;
              deleteAction(that.url.delete, {invateuserdetailId: invateuserdetailId}).then((res) => {
                if (res.success) {
                  that.$message.success(res.message);
                  that.loadData();
                } else {
                  that.$message.warning(res.message);
                }
              });
            },


         keyupEnter(){
                    document.onkeydown = e =>{
                        if (e.keyCode === 13  ) {
                           this.loadData(1);
                        }
                    }
                },

        }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>